package com.kacheap.service;

import java.time.LocalDateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

@Service
public class RemoteApiService {
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * @Retryable注解，value值表示当哪些异常的时候触发重试，maxAttempts表示最大重试次数默认为3，delay表示重试的延迟时间，multiplier表示上一次延时时间是这一次的倍数。
	 * @Recover注解，当重试次数达到设置的次数的时候，还是失败抛出异常，执行的回调函数。
	 * @param num
	 * @return
	 * @throws Exception
	 */
	@Retryable(retryFor = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 1.5))
	public boolean pay(int num) throws Exception {
		
		//mock exception
		if (num == 0) {
			logger.info("invoke third method failure");
			throw new Exception("error，need retry");
		}
		
		logger.info("invoke third method successful");
		
		return true;
	}

	/**
	 * 最终失败后的处理结果
	 * @param num
	 * @return
	 * @throws Exception
	 */
	@Recover
	public boolean recover(int num) throws Exception {
		logger.info("recover ... {}, {}", num, LocalDateTime.now());
		return false;
	}

}